package co.com.smart.eagle.bean.application;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;

import co.com.smart.eagle.entities.EagleSecurityApplications;
import co.com.smart.eagle.infrastructure.dto.AplicacionesDTO;
import co.com.smart.eagle.infrastructure.dto.SmartExcepcionSerializada;
import co.com.smart.eagle.mapper.Mapper;
import co.com.smart.eagle.persistence.entity.ApplicationsFacadeLocal;
import co.com.smart.eagle.session.DelegateContextEJB;

/**
 * Session Bean implementation class ApplicationBean
 */
@Stateless(mappedName = "ejb/ApplicationBean")
public class ApplicationBean implements ApplicationBeanLocal {

	private ApplicationsFacadeLocal facade;

	/**
	 * Default constructor.
	 */
	public ApplicationBean() {
		facade = DelegateContextEJB.getApplicationsFacadeLocal();
	}

	@Override
	public List<AplicacionesDTO> getApplications() {
		List<AplicacionesDTO> applications = new ArrayList<AplicacionesDTO>();
		List<EagleSecurityApplications> applicationsEntity = facade.findAll();
		if (applicationsEntity != null) {
			for (EagleSecurityApplications eagleSecurityApplications : applicationsEntity) {
				applications.add(Mapper.mapperAplicaciones(eagleSecurityApplications)) ;
			}
		}
		return applications;
	}

	@Override
	public void setApplication(AplicacionesDTO app) throws Exception {
		EagleSecurityApplications entityApp = facade.find(app.getDsAplicacion());
		if (entityApp != null) {
			throw new SmartExcepcionSerializada("La aplicacion ya existe, por favor usar otro nombre");
		}
		entityApp = Mapper.mapperEntityApplications(app);
		facade.create(entityApp);
	}

	@Override
	public void deleteApplication(AplicacionesDTO app) throws Exception {
		try {
			EagleSecurityApplications entityApp = Mapper.mapperEntityApplications(app);
			facade.remove(entityApp);
		} catch (Throwable ex ) {
			throw new SmartExcepcionSerializada("No es posible eliminar el registro, Dependencia de datos");
		}
	}

}
